(function($){
	$.fn.extend({
		dcTree:function(options){
			var self=$(this);
			self.attr("readOnly",true);
			options=$.extend({
				id:self.attr("id"),// id
				returnKey:"nodeCode",
				dictType:self.attr("dictType"),
				dictId:self.attr("dictId"),
				levelNo:self.attr("levelNo"),
				treeId:"myZtree_"+self.attr("id"),
				menuContent:"#menuContent_"+self.attr("id"),//显示菜单样式
				menuContentId:"menuContent_"+self.attr("id"),//显示菜单样式
				expandAllBtnTag:"#expandAllBtn",
				collapseAllBtnTag:"#collapseAllBtn",
				checkbox:typeof self.attr("checkbox")!="undefined",//是否有复选框
				asyn:true,//是否动态
				url:function(){
					var url= webRoot+"/sys/dict/queryDictTreeByDicType.json"+"?dictType="+options.dictType;
					if(options.levelNo){
						url+="&levelNo="+options.levelNo;
					}
					return url;
				},
				otherParam:{
						search_EQ_dictType:function(){return self.attr("dictType")}(),
						search_EQ_levelNo:function(){return self.attr("levelNo")}()
						},
				empty_select:false,
				otherParam:{dictType:function(){return self.attr("dictType")},levelNo:function(){return self.attr("levleNo")}},
				canSelect:function(nodes,value){
					if(value==""&&(!options.empty_select)){
						return false;
					}
					return true
				},
				// 数据配置
				setting_data_simpleData_enable:true,
				setting_data_simpleData_idKey:"id",
				setting_data_simpleData_searchKey:"id=search_EQ_id",
				setting_data_simpleData_pIdKey:"parentId",
				setting_data_simpleData_rootPId:"0",//root
				setting_data_key_name:"displayName", //名称显示
				// 显示配置
				setting_view_showLine:true,
				setting_view_showIcon:true,
				setting_view_selectedMulti:false,
				setting_view_expandSpeed:"normal",
				setting_edit_enable:false,
				chkboxType: { "Y" : "ps", "N" : "ps" },
				addFun:false,
				editFun:false,
				detailFun:false,
				deleteFun:false,
				dropFun:false,
				/***
				 * 获取树对象
				 */
				getTree:function(){
					return $.fn.zTree.getZTreeObj(options.treeId);
				},
				/**
					点击前的事件
				*/
				beforeClick:function(treeId, treeNode){
					if(options.checkbox){
						var zTree = options.getTree();
						zTree.checkNode(treeNode, !treeNode.checked, null, true);
						return false;
					}
				},
				
				/**
				  拖动前调用
				*/
				beforeDrop:function beforeDrop(treeId, treeNodes, targetNode, moveType) {
					//console.log("treeId="+treeId+", treeNodes="+treeNodes[0].displayName+", targetNode="+targetNode.displayName+", moveType="+moveType);
					if(options.dropFun){
						options.dropFun(treeId,treeNodes,targetNode,moveType);
						return true;
					}
					return false;
				},
				
				/**
				  删除调用
				*/
				onDrop: function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy){
				},
				
				/**
				   点击方法 单选按钮使用
				*/
				onClick:function(){//单选用
					if(options.dictId){						
						var zTree = options.getTree();
						var nodes = zTree.getSelectedNodes();
						var dictId="",name="";
						name = nodes[0][options.setting_data_key_name];
						dictId = nodes[0][options.returnKey];
						if(options.canSelect(nodes,dictId)){
							self.val(name);
							$("#"+options.dictId).val(dictId).trigger("blur");
							self.trigger("focus").trigger("blur").trigger("dcTree.change",nodes);
							options.hideTree();
						}
					}
				},
				
				
				/***
				  复选框 方法 将内容 存放在 dictId的数据中，
				*/
				onCheck:function(e, treeId, treeNode) {//复选用
					if(options.asyn){
						id = ""+treeNode[options.returnKey]+"";
						var d = $("#"+self.attr("dictId")).val();
						var n = self.val();
						var names = n.split(",");
						//如果勾选
						if(treeNode.checked){
							if(d.indexOf(id)<0){
								names.push(treeNode[options.setting_data_key_name]);
								$("#"+self.attr("dictId")).val(d+","+id);
							}
						}else{//去掉勾选
							if(d.indexOf(id)>-1){
								d = d.replace(new RegExp(""+treeNode.id+",",'g'),'');
								for(var i=0;i<names.length;i++){
									if(names[i]==treeNode[options.setting_data_key_name]){
										names.splice(i,1);
									}
								}
								$("#"+options.dictId).val(d);
							}
						}
						for(var i=0;i<names.length;i++){
							if(names[i]==''){
								names.splice(i,1);
							}
						}
						self.val(names.join(","));
					}else{
						var zTree =  options.getTree();
						var nodes = zTree.getCheckedNodes(true);
						var dictId="",name="";
						for(var i=0;i<nodes.length;i++){
							name+=nodes[i][options.setting_data_key_name]+",";
							dictId+=""+nodes[i][options.returnKey]+",";
						}
						if(nodes.length>1){
							name=name.substring(0,name.length-1);
							dictId=dictId.substring(0,dictId.length-1);
						}
						self.val(name);
						$("#"+options.dictId).val(dictId);
					}
					
						self.trigger("dcTree.change");
					
				},
				
				/**
					初始化方法
				*/
				init:function(){
					
					var html='<div id="'+options.menuContentId+'" class="menuContent" style="position: absolute; z-index: 999999; overflow-y:auto;overflow-x:hidden; top:23px;">';
						html+='	<ul id="'+options.treeId+'" class="ztree myZtree" style="margin-top:0;margin-bottom:30px; padding-bottom:30px;height:150px; overflow-y:auto;  border:1px solid #E4E4E4;"></ul>';
						html+='</div>';
						if($(options.menuContent).length==0){
							$("body").append(html);
						}
						if(options.asyn){
							$.fn.zTree.init($("#"+options.treeId), options.setting());
						}else{
							common.send(($.isFunction(options.url)?options.url():options.url),{"queryAll":"true"},function(data){
				 			       if(data!=null){
								      zNodes = data;
								      options.filter("","",zNodes);
								       var zTree = $.fn.zTree.init($("#"+options.treeId), options.setting(),zNodes);
								       zTree.expandAll(true);
								       setTimeout(function(){
										      var hideId=$("#"+options.dictId).val();
										      if(options.checkbox){
										    	  var list=hideId.split(",");
										    	  for(var i=0;i<list.length;i++){
										    		  var node=zTree.getNodeByParam("id",list[i],null);
										    		  if(node){
										    			  zTree.checkNode(node, true, false, true);
										    		  }
										    	  }
										      }
								       
								       },10);
							       }

					 	       });
							}
				},
				
				/**
					过滤 ，将 root复选框去掉，非叶子节点的删除功能去掉
					FEXIE
				*/
				filter:function(treeId, parentNode, childNodes) {
					if (!childNodes) return null;
					for (var i=0, l=childNodes.length; i<l; i++) {
						//如果是根节点，则去掉复选框
						if(childNodes[i].levelNo==0){
							childNodes[i].nocheck=true;
						}
						//先设置默认为不是上级
						childNodes[i].isParent=false;
						if(childNodes[i].nodeType.code!="LEAF"){
							childNodes[i].isParent=true;
						}
						//树根节点不可以拖动
						childNodes[i].dropRoot=false;
					}
					return childNodes;
				},
				
				/**
				 * 显示一棵树
				 */
				showTree:function(){
					if(!options.initFlag){
						options.initFlag=true;
						options.init();
					}
					$("body").unbind("mousedown",options.onBodyDown);
					$(options.menuContent).hide();
					var offset=self.offset();
					$(options.menuContent).css({
							left:offset.left+"px",
							top:offset.top+self.outerHeight()+"px"
							}).slideDown("fast");
					if(options.dictId){
						$("body").bind("mousedown",options.onBodyDown);
					}
				},
				
				hideTree:function(){
					if(options.dictId){
						$(options.menuContent).fadeOut("fast");
						$("body").unbind("mousedown",options.onBodyDown);
					}
				},
				
				
				onBodyDown:function(event){
					if($(event.target).closest(options.menuContent).length==0){
						options.hideTree();
					}
				},
				
					/**
					添加自定义按钮
				*/
				addHoverDom:function(treeId, treeNode) {
						var aObj = $("#" + treeNode.tId + "_a");
						
						if (aObj.data("btn")) return;
						aObj.data("btn",true)
						var addStr ="";
						if(options.addFun){
							addStr		 +=  "<button type='button'  class='icon01' id='addBtn_" +treeNode.id+ "' title='添加' />";
						}
						if(options.detailFun){
	
							addStr		 +=  "<button type='button'  class='button detail' id='detailBtn_" +treeNode.id+ "' title='详细' />";
						}
						
						if(options.editFun){
							addStr 		+=  "<span  class='button edit' id='editBtn_" +treeNode.id+ "' title='修改'/>";
						}
						
						if(options.deleteFun){
							if(!treeNode.isParent&&treeNode.nodeType.code!="ROOT"){//根节点不能删除
								addStr		+=  "<span  class='button remove' id='removeBtn_" +treeNode.id+ "' title='删除' />";
							}
						}
					
						aObj.find("span:eq(1)").append(addStr);
						//给添加绑定事件
						var addBtn = $("#addBtn_"+treeNode.id);
						
						addBtn.bind("click", function(){options.addFun(treeNode);return false;});
						
						var editBtn = $("#editBtn_"+treeNode.id);
						editBtn.bind("click",function(){options.editFun(treeNode);return false;});
	
						var detailBtn=$("#detailBtn_"+treeNode.id);
						
						detailBtn.bind("click",function(){options.detailFun(treeNode);return false;})
						
						var removeBtn = $("#removeBtn_"+treeNode.id);
						removeBtn.bind("click",function(){
							var treeId=treeNode.id;
							common.confirm("你确定要删除该信息吗？",function(result){
								if(result){
									options.deleteFun(treeId);
								}
							});
							return false;
						});
				},
				
				removeHoverDom:function (treeId, treeNode) {
						$("#addBtn_"+treeNode.id).unbind().remove();
						$("#editBtn_" +treeNode.id).unbind().remove();
						$("#removeBtn_" +treeNode.id).unbind().remove();
						$("#detailBtn_" +treeNode.id).unbind().remove();
						var aObj = $("#" + treeNode.tId + "_a");
						aObj.removeData("btn");
				},
				
				
				// 设置
				setting:function(){
					
					var result= {
							edit:{
								enable: options.setting_edit_enable,
								showRemoveBtn: false,
								showRenameBtn: false
							},
							data: {
								simpleData: {
									enable: options.setting_data_simpleData_enable,
									idKey: options.setting_data_simpleData_idKey,
									pIdKey:options.setting_data_simpleData_pIdKey,
									rootPId:options.setting_data_simpleData_rootPId
								},
								key:{
									name:options.setting_data_key_name
								}
							},
							async: {
								enable: options.asyn,
								url:options.url,
								autoParam:[options.setting_data_simpleData_searchKey],
								otherParam:options.otherParam,
								dataType: "json",
								dataFilter: options.filter
								
							},
							view: {
								showLine:options.setting_view_showLine,
								showIcon:options.setting_view_showIcon,
								selectedMulti: options.setting_view_selectedMulti,
								expandSpeed: options.setting_view_expandSpeed,
								addHoverDom: options.addHoverDom,
								removeHoverDom:options.removeHoverDom
							},
							//回调
							callback: {
								beforeClick: options.beforeClick,
								onClick: options.onClick,
								onCheck:options.onCheck,
								beforeDrop:options.beforeDrop,
								onDrop:options.onDrop
							}
						}
					
						if(typeof self.attr("checkbox")!="undefined"){
							result["check"]=
								{
									enable: true,
									chkboxType: options.chkboxType
								};
						}
						return result;
					}
			},options);
			
			var timeout;
			
			$(self).bind("click",function(){
				clearTimeout(timeout);
				var self=$(this);
				timeout=setTimeout(function(){
					options.showTree();
				},300);
			});
			
			$(self).bind("dblclick",function(){
				clearTimeout(timeout);
				var self=$(this);
				options.initFlag=false;
				options.showTree();
			});
			
			
			/**
			 * 全部展开 
			 */
			$(options.expandAllBtnTag).click(function(){
				var zTree = options.getTree();
				var nodes = zTree.getSelectedNodes();
				if(nodes.length==0){
					zTree.expandAll(true);
				}else{
					for(var i=0;i<nodes.length;i++){
						zTree.expandNode(nodes[i], true, true, true, true);
					}
				}
			});
			
			/**
			 * 全部合拢
			 */
			$(options.collapseAllBtnTag).click(function(){
				var zTree = options.getTree();
				var nodes = zTree.getSelectedNodes();
				if(nodes.length==0){
					zTree.expandAll(false);
				}else{
					for(var i=0;i<nodes.length;i++){
						zTree.expandNode(nodes[i], false, true, false, false);
					}
				}
			});
			
			var DcTree=function DcTree(){};
			
			DcTree.prototype.addTreeCallBack=function(node){
				var zTree = options.getTree();
				var treeNode=zTree.getNodeByParam("id",node.parentId);
				if(!treeNode.isParent||treeNode.open){
					zTree.addNodes(treeNode, node);
					zTree.updateNode(treeNode);
				}else{
					zTree.expandNode(treeNode, true, null, null,false);
				}
			}
			
			DcTree.prototype.editTreeCallBack=function(node){
				var zTree = options.getTree();
				var treeNode=zTree.getNodeByParam("id",node.id);
				treeNode.displayName=node.displayName;
				zTree.updateNode(treeNode);
			}
			
			DcTree.prototype.removeById=function(treeId){
				var zTree = options.getTree();
				var treeNode=zTree.getNodeByParam("id",treeId);
				zTree.removeNode(treeNode,false);
			}
			
			return new DcTree();	
		}
	})
})(jQuery)